package com.xxx.springboot.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xxx.springboot.annotation.LoginAuth;
import com.xxx.springboot.constant.Constants;
import com.xxx.springboot.exception.NotLoginException;

/**
 * 登录校验拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Value("${spring.profiles.active}")
	private String env;

	/**
	 * This is used to perform operations before sending the request to the controller. 
	 * This method should return true to return the response to the client.
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
			throws Exception {
		if (handler instanceof HandlerMethod) {
			final HandlerMethod handlerMethod = (HandlerMethod) handler;
			final Method method = handlerMethod.getMethod();
			final Class<?> clazz = method.getDeclaringClass();
			if (clazz.isAnnotationPresent(LoginAuth.class) ||
					method.isAnnotationPresent(LoginAuth.class)) {
				if (null == request.getSession().getAttribute(Constants.USER_INFO_SESSION_KEY)) {
//					 if ("test".equals(env)) { //  测试环境设置默认用户，方便调试
//						 UserInfo userInfo = new UserInfo();
//						 userInfo.setUserId(1);
//						 userInfo.setUserName("admin");
//						 userInfo.setRealName("顾");
//						 userInfo.setMobile("18612345678");
//						 userInfo.setEmail("abc@123.com");
//						 userInfo.setSex(1);
//						 userInfo.setPositionId(2);
//						 request.getSession().setAttribute(Constants.USER_INFO_SESSION_KEY, userInfo);
//						 return true;
//					 }
					 throw new NotLoginException();
				}
			}
		}

		return true;
	}

	/**
	 * This is used to perform operations before sending the response to the client.
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {

	}

	/**
	 * This is used to perform operations after completing the request and response.
	 * @param request
	 * @param response
	 * @param handler
	 * @param ex
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
